package com.gdpu.pbss.controller;



import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gdpu.pbss.common.Result;
import com.gdpu.pbss.mapper.FileMapper;
import com.gdpu.pbss.pojo.Files;

import com.gdpu.pbss.pojo.Manager;
import com.gdpu.pbss.pojo.User;
import com.gdpu.pbss.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
@RestController
@RequestMapping("/file")
public class FileController {


    @Value("${files.upload.path}")
    private String fileUploadPath;

    @Autowired
    private FileMapper fileMapper;


    @PostMapping("/upload")
    public String upload(@RequestParam MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        String type = FileUtil.extName(originalFilename);
        long size = file.getSize();

        // 定义一个文件唯一的标识码
        String uuid = IdUtil.fastSimpleUUID();
        String fileUUID = uuid + StrUtil.DOT + type;

        File uploadFile = new File(fileUploadPath + fileUUID);
        // 判断配置的文件目录是否存在，若不存在则创建一个新的文件目录
        File parentFile = uploadFile.getParentFile();
        if(!parentFile.exists()) {
            parentFile.mkdirs();
        }


        String url;
        // 获取文件的md5
        String md5 = SecureUtil.md5(file.getInputStream());
        // 从数据库查询是否存在相同的记录
        Files dbFiles = getFilesByMd5(md5);
        if (dbFiles != null) { // 文件已存在
            url = dbFiles.getUrl();
            uploadFile.delete();
        } else {
            // 上传文件到磁盘
            file.transferTo(uploadFile);
            // 数据库若不存在重复文件，则不删除刚才上传的文件
            url = "http://localhost:9090/file/" + fileUUID;
        }

        //存储到数据库
        Files savefile=new Files();
        savefile.setName(originalFilename);
        savefile.setSize(size/1024);
        savefile.setType(type);
        savefile.setUrl(url);
        savefile.setMd5(md5);

        fileMapper.insert(savefile);
        return url;

    }

    @GetMapping("/{fileUUID}")
    public void download(@PathVariable String fileUUID, HttpServletResponse response) throws IOException {
        // 根据文件的唯一标识码获取文件
        File uploadFile = new File(fileUploadPath + fileUUID);
        // 设置输出流的格式
        ServletOutputStream os = response.getOutputStream();
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileUUID, "UTF-8"));
        response.setContentType("application/octet-stream");

        // 读取文件的字节流
        os.write(FileUtil.readBytes(uploadFile));
        os.flush();
        os.close();
    }

    public Files getFilesByMd5(String md5){
        QueryWrapper<Files> qw=new QueryWrapper<>();
        qw.eq("md5",md5);
        List<Files> filesList = fileMapper.selectList(qw);
        return filesList.size()== 0? null:filesList.get(0);
    }

    @PostMapping("/update")
    public Result updateFiles(@RequestBody Files files){
        return Result.success(fileMapper.updateById(files));
    }

    @GetMapping("/page")
    public Result selectFilePage(@RequestParam Integer pageNum, @RequestParam Integer pageSize,
                                      @RequestParam(defaultValue = "") String name

    ){


        IPage<Files> page=new Page<>(pageNum,pageSize);
        QueryWrapper<Files> qw =new QueryWrapper<>();
       qw.eq("is_delete",false);
        if (!"".equals(name)) {
            qw.like("name", name);
        }
      qw.orderByDesc("id");


        return Result.success(fileMapper.selectPage(page,qw));

    }

    @DeleteMapping("/{id}")
    public Result deleteFile(@PathVariable("id") Integer id){
        QueryWrapper<Files> qw=new QueryWrapper<>();
        qw.eq("id",id);

        Files selectOne = fileMapper.selectOne(qw);
        selectOne.setIsDelete(true);
        fileMapper.updateById(selectOne);

        return Result.success();
    }
    @PostMapping("/del/batch")
    public Result deleteBatch(@RequestBody List<Integer> ids){

           QueryWrapper<Files> qw=new QueryWrapper<>();
           qw.in("id",ids);
        List<Files> files = fileMapper.selectList(qw);
        for (Files file : files) {
            file.setIsDelete(true);
            fileMapper.updateById(file);
        }
        return Result.success();

    }

}
